package fr.univ.surveyonline.tags;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import fr.univ.surveyonline.language.Language;

public class LanguageTag extends TagSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String id = null;
	
	public void setId(String id) {
		if ((id == null) || (id.length() ==0)) {
			throw new IllegalStateException("L'id est vide");
		}
		this.id = id;
	}
	
	public int doStartTag() throws JspException	{
		if (id == null) {
			throw new IllegalStateException("Le tag doit obligatoirement avoir l'attribut 'id'");
		}
		HttpServletRequest req =  (HttpServletRequest) this.pageContext.getRequest();
		String langue = null;
		try {
			for (Cookie c : req.getCookies()) {
				if (c.getName().equals("langue")) {
					langue = c.getValue(); 
					break;
				}
			}
		} catch (Exception e) {
			
		}
		if (langue == null) {
			HttpServletResponse resp =  (HttpServletResponse) this.pageContext.getResponse();
			Cookie c = new Cookie("langue","FR");
			langue = "FR";
			resp.addCookie(c);
		}
		
		JspWriter out = pageContext.getOut();
		try {
			out.println(Language.getWord(id,langue));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SKIP_BODY;		
	}

}
